package com.ossdemo.strategy.impl;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.ListObjectsV2Result;
import com.aliyun.oss.model.OSSObjectSummary;
import com.ossdemo.config.properties.OssProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service("ossUploadStrategyImpl")
public class OssUploadStrategyImpl extends AbstractUploadStrategyImpl {
    @Autowired
    private OssProperties ossProperties;

    /**
     * 判断文件是否存在
     *
     * @param filePath 文件路径
     * @return
     */
    @Override
    public Boolean exists(String filePath) {
        boolean flag = false;
        try {
            flag = getOssClient().doesObjectExist(ossProperties.getBucketName(), filePath);
        } catch (Exception e) {
            return false;
        }
        return flag;
    }

    @Override
    public void upload(String path, String fileName, InputStream inputStream) {
        OSS ossClient = getOssClient();
        try {
            // 调用oss方法上传
            ossClient.putObject(ossProperties.getBucketName(), path + fileName, inputStream);
        } catch (OSSException oe) {
            log.error("Error Message:" + oe.getErrorMessage());
            log.error("Error Code:" + oe.getErrorCode());
            log.info("Request ID:" + oe.getRequestId());
            log.info("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            log.error("Caught an ClientException, Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }

    @Override
    public String getFileAccessUrl(String filePath) {
        return ossProperties.getUrl() + filePath;
    }

    /**
     * 获取ossClient
     *
     * @return {@link OSS} ossClient
     */
    private OSS getOssClient() {
        return new OSSClientBuilder().build(ossProperties.getEndpoint(), ossProperties.getAccessKeyId(), ossProperties.getAccessKeySecret());
    }

    /**
     * 获取相册
     * @param path 文件夹
     * @return
     */
    @Override
    public List<String> getAllPicture(String path) {
        List<String> list = new ArrayList<>();

        OSS ossClient = getOssClient();
        ListObjectsV2Result results = ossClient.listObjectsV2(ossProperties.getBucketName(), path);
        List<OSSObjectSummary> ossObjectSummaries = results.getObjectSummaries();
        for (OSSObjectSummary s : ossObjectSummaries) {
            System.out.println("00===============================\t" + s.getKey());
            list.add(ossProperties.getUrl() + "/" + s.getKey());
        }
        return list;
    }
    /**
     * 删除图片
     * @param path 图片地址
     * @return true 删除成功 false 删除失败
     */
    @Override
    public boolean deletePicture(String path) {
        // +1 是为了把/去掉
        int len  =  ossProperties.getUrl().length()+1;
        // 截取文件名
        String pictureName = path.substring(len);
        try {
            // 删除文件或目录。如果要删除目录，目录必须为空。
            getOssClient().deleteObject(ossProperties.getBucketName(), pictureName);
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
            return false;
        } finally {
            if (getOssClient() != null) {
                getOssClient().shutdown();
            }
        }
        System.out.println("==============删除文件成功==="+pictureName+len);
        return true;
    }
}

